# -*- coding: utf-8 -*-
import sys
from PySide import QtGui, QtCore


class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.init_data()
        self.init_ui()
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.timeout)
        self.timer.start(100)

    def init_data(self):
        self.size = 128
        self.scale_rat = 16
        self.actual_size = 16
        self.img = None
        self.color = None

    def init_ui(self):
        self.setFixedSize(self.size, self.size)
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

    def paintEvent(self, event):
        qp = QtGui.QPainter()
        qp.begin(self)
        self.draw(qp)
        qp.end()

    def draw(self, qp):
        if not self.img:
            return

        qp.drawImage(self.rect(), self.img)
        qp.fillRect(0, 0, self.rect().width(), 20, QtGui.QColor(200, 200, 200))
        rgb = '%d, %d, %d' % (self.color >> 16 & 0xff, self.color >> 8 & 0xff, self.color & 0xff)
        qp.drawText(self.rect(), QtCore.Qt.AlignLeft, rgb)
        qp.drawRect(self.width()/2, self.height()/2, 8, 8)

    def get_data(self):
        img = QtGui.QPixmap.grabWindow(QtGui.QApplication.desktop().winId()).toImage()
        pos = self.cursor().pos()
        x, y = pos.x(), pos.y()
        self.color = img.pixel(x, y)
        self.img = img.copy(x - self.actual_size/2, y - self.actual_size/2, self.actual_size, self.actual_size)

    def timeout(self):
        self.get_data()
        self.update()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    widget = Window()
    widget.show()
    sys.exit(app.exec_())
